package v2.parser.load


import java.io.{FileWriter, File}
import v2.parser.tree.{TypedTree, Navigation}

/**
 * 
 * Load/Save deals with navigation objects.  To edit the tree after loading, you 
 * must switch to edit mode 
 * 
 * @author bweber
 * @version $Rev$, $Date$
 */

class Loader private {
  def load(fileName:String):Navigation = {
    val content = scala.io.Source.fromFile(fileName).mkString
    val value = Unpickler(content)
    val typedTree = TypedTree("root",value(0))
    Navigation(typedTree)
  }
}

object Loader {
  def apply() = {
    new Loader().load(".typed-tree")
  }
  def apply(fileName:String) = {
    new Loader().load(fileName)
  }
}

class Saver private {
  def save(fileName:String,nav:Navigation) {
    nav.root_cd
    val root = nav.currentTree.currentNode
    val content = Pickler(root)
    var fileWriter:FileWriter = null
    try {
      fileWriter = new FileWriter(new File(fileName))
      fileWriter.write(content)
    }
    catch {
      case e:Exception => throw new RuntimeException("Unable to save to [" + fileName + "]",e)
    }
    finally {
      if ( fileWriter != null ) {
        fileWriter.close()
      }
    }
  }
  
}

object Saver {
  def apply(nav:Navigation) {
    new Saver().save(".typed-tree",nav)
  }
}